from flask import Blueprint, render_template, request, current_app, abort, redirect, url_for, flash
from flask_login import login_required, current_user
from app import db
from app.models.post import Post
from app.models.tag import Tag
from app.models.comment import Comment
from app.forms.main import CommentForm

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.filter_by(published=True).order_by(Post.created.desc()).paginate(
        page=page, per_page=current_app.config['POSTS_PER_PAGE'], error_out=False)
    return render_template('main/index.html', posts=posts)

@main_bp.route('/post/<string:slug>')
def post(slug):
    post = Post.query.filter_by(slug=slug, published=True).first_or_404()
    post.increment_views()
    form = CommentForm()
    return render_template('main/post.html', post=post, form=form)

@main_bp.route('/tag/<string:slug>')
def tag(slug):
    tag = Tag.query.filter_by(slug=slug).first_or_404()
    page = request.args.get('page', 1, type=int)
    posts = tag.posts.filter_by(published=True).order_by(Post.created.desc()).paginate(
        page=page, per_page=current_app.config['POSTS_PER_PAGE'], error_out=False)
    return render_template('main/tag.html', tag=tag, posts=posts)

@main_bp.route('/about')
def about():
    return render_template('main/about.html')

@main_bp.route('/contact')
def contact():
    return render_template('main/contact.html')

@main_bp.route('/post/<int:post_id>/comment', methods=['POST'])
@login_required
def comment(post_id):
    post = Post.query.get_or_404(post_id)
    form = CommentForm()
    
    if form.validate_on_submit():
        try:
            comment = Comment(
                body=form.body.data,
                post_id=post.id,
                author_id=current_user.id
            )
            db.session.add(comment)
            db.session.commit()
            flash('评论已发布', 'success')
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f'评论发布失败: {str(e)}')
            flash('评论发布失败，请稍后再试', 'danger')
    else:
        for field, errors in form.errors.items():
            for error in errors:
                flash(f'{getattr(form, field).label.text}: {error}', 'danger')
    
    return redirect(url_for('main.post', slug=post.slug))

@main_bp.route('/comment/<int:comment_id>/reply', methods=['POST'])
@login_required
def reply(comment_id):
    parent_comment = Comment.query.get_or_404(comment_id)
    form = CommentForm()
    
    if form.validate_on_submit():
        try:
            reply = Comment(
                body=form.body.data,
                post_id=parent_comment.post_id,
                author_id=current_user.id,
                parent_id=parent_comment.id
            )
            db.session.add(reply)
            db.session.commit()
            flash('回复已发布', 'success')
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f'回复发布失败: {str(e)}')
            flash('回复发布失败，请稍后再试', 'danger')
    else:
        for field, errors in form.errors.items():
            for error in errors:
                flash(f'{getattr(form, field).label.text}: {error}', 'danger')
    
    return redirect(url_for('main.post', slug=parent_comment.post.slug))